package chances.wechat.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class HTTPPoster {
	public static String post(String urlstr, File file) throws IOException {
		String content = FileUtils.readFileToString(file);
		return post(urlstr, content);
	}

	public static String post(String urlstr, String xmlString) throws IOException {
		DataInputStream input = null;
		ByteArrayOutputStream out = null;
		byte[] xmlData = xmlString.getBytes();
		try {
			URL url = new URL(urlstr);
			URLConnection urlCon = url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
			DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
			printout.write(xmlData);
			printout.flush();
			printout.close();
			return getReponse(urlCon);

		} catch (IOException e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(input);
		}
	}

	protected static String getReponse(URLConnection urlCon) throws IOException {
		DataInputStream input = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		try {
			input = new DataInputStream(urlCon.getInputStream());
			IOUtils.copy(input, out);
			return new String(out.toByteArray(), "UTF-8");
		} catch (IOException e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(input);
		}

	}

}
